<template>
  <div class="box">
    <div class="top">
      当前录入试题类型：
      <el-select :disabled="true" v-if="!props.serialNumber" v-model="form.questionTypeName" size="large"
        @change="questionSelect">
        <el-option v-for="item in questiontypeList" :key="item.dbName" :label="item.dbName" :value="item.dbName" />
      </el-select>
      <strong v-if="props.serialNumber">试题编号:{{ props.serialNumber }}</strong>
    </div>
    <div class="ipt">
      <el-form ref="formIpt" :model="form" label-width="85px" :show-message="false" :validate-on-rule-change="false">
        <el-row class="knowledge" v-if="knowledgeShow && config.knowledge == '1'">
          <el-col class="labelwidth require" :span="1.5">知识点</el-col>
          <el-col :span="6" v-for="(item, i) in form.knowledge" :key="i" class="item">
            <el-tree-select placeholder="请选择" :default-expanded-keys="defaultList" v-model="item.knowledgeId"
              :data="knowledgeList" check-strictly :render-after-expand="false" />
            <div style="width: 19%; margin: 0 6px 0 0">
              <el-input v-model="item.percentUiValue">
                <template #append>%</template>
              </el-input>

            </div>
            <el-button class="mt" type="danger" size="small" :icon="Delete" @click="KnowDel(i)" circle plain />
          </el-col>
          <el-button class="addBtn" :icon="CirclePlus" @click="knowAdd" plain>添加知识点</el-button>
        </el-row>
        <div v-else style="height:50px"></div>
        <el-row>
          <el-col :span="6" v-if="config.useful == '1'">
            <el-form-item label="题目用途" label-width="92px">
              <el-select collapse-tags v-model="form.basicData['questionBasic-basicUseful']" multiple
                @change="userfulChange" placeholder="请选择">
                <el-option v-for="item in usefulList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.difficult == '1'">
            <el-form-item label="难易程度" label-width="92px">
              <span class="required" style="transform: translateX(-75px);">*</span>
              <el-select v-model="form.basicData['questionBasic-basicDifficult']" placeholder="请选择">
                <el-option v-for="item in difficultList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.ability == '1'">
            <el-form-item label="能力" label-width="50px">
              <span class="required" style="transform: translateX(-45px);">*</span>
              <el-select v-model="form.basicData['questionBasic-basicAbility']" placeholder="请选择">
                <el-option v-for="item in abilityList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.require == '1'">
            <el-form-item label="教学要求度">
              <el-select v-model="form.basicData['questionBasic-require']" placeholder="请选择">
                <el-option v-for="item in requireList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.examType == '1'">
            <el-form-item label="考试类型">
              <el-select v-model="form.basicData['questionBasic-examType']" placeholder="请选择">
                <el-option v-for="item in examTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="config.tikabianhao == '1'">
            <el-form-item label="题卡编号" label-width="92px">
              <el-input :style="'width:' + inputWidth + 'px;'"
                v-model="form.basicData['questionBasic-oldSerialNumber']"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.tuisonglitihao == '1'">
            <el-form-item label="推送例题号" label-width="92px">
              <el-input :style="'width:' + inputWidth + 'px;'"
                v-model="form.basicData['questionBasic-exampleQuestion']"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.zhenTi == '1'">
            <el-form-item label="是否真题">
              <el-select :style="'width:' + inputWidth + 'px;'" v-model="form.basicData['questionBasic-zhenTi']"
                placeholder="请选择">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6" v-if="form.basicData['questionBasic-zhenTi'] == '1' && config.zhenTi == '1'">
            <el-form-item label="真题属性">
              <el-input :style="'width:' + inputWidth + 'px;'"
                v-model="form.basicData['questionBasic-zhenTiProp']"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.basicData['questionBasic-zhenTi'] == '1' && config.zhenTi == '1'">
            <el-form-item label="真题学校">
              <el-input :style="'width:' + inputWidth + 'px;'"
                v-model="form.basicData['questionBasic-zhenTiSchool']"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.basicData['questionBasic-zhenTi'] == '1' && config.zhenTi == '1'">
            <el-form-item label="真题年份">
              <el-input :style="'width:' + inputWidth + 'px;'"
                v-model="form.basicData['questionBasic-zhenTiYear']"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="6" v-if="config.relationGroup == '1'">
            <el-form-item label="相关题组">
              <el-select :style="'width:' + inputWidth + 'px;'" v-model="form.basicData['questionBasic-relationGroupId']"
                filterable placeholder="请选择">
                <el-option v-for="k in questionAll.relation" :key="k.id" :label="k.name" :value="k.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.equalGroup == '1'">
            <el-form-item label="等效题组">
              <el-select :style="'width:' + inputWidth + 'px;'" v-model="form.basicData['questionBasic-equalGroupId']"
                filterable placeholder="请选择">
                <el-option v-for="k in questionAll.equal" :key="k.id" :label="k.name" :value="k.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.excludeGroup == '1'">
            <el-form-item label="互斥题组">
              <el-select :style="'width:' + inputWidth + 'px;'" v-model="form.basicData['questionBasic-excludeGroupId']"
                filterable placeholder="请选择">
                <el-option v-for="k in questionAll.exclude" :key="k.id" :label="k.name" :value="k.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.schoolType == '1'">
            <el-form-item label="学校类型">
              <el-select :style="'width:' + inputWidth + 'px;'" v-model="form.basicData['questionBasic-schoolType']"
                placeholder="请选择">
                <el-option v-for="k in questionAll.schoolType" :label="k.name" :value="k.id" :key="k.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="config.majorType == '1'">
            <el-form-item label="专业类型">
              <el-select :style="'width:' + inputWidth + 'px;'" v-model="form.basicData['questionBasic-majorType']"
                placeholder="请选择">
                <el-option v-for="k in questionAll.major_type" :label="k.name" :value="k.id" :key="k.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题备注" v-if="config.source == '1'">
              <el-input :style="'width:' + inputWidth + 'px;'" v-model="form.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题提供者" v-if="config.provider == '1'">
              <el-input :style="'width:' + inputWidth + 'px;'" v-model="form.provider"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-affix :offset="0" :z-index="affixZIndex">
      <div id="EditTinId">
        <!-- 工具栏位置 -->
        <div class="toolbarTips" v-if="toolbarTips">
          编辑器工具栏，编辑试题时自动激活
        </div>
      </div>
    </el-affix>
    <div class="EditTin" v-if="EditShow">
      <div v-if="form.questionTypeBase == 'pan_duan'">
        <panDuan v-model="form" :zhengque="config.judgeQuestionRight" :cuowu="config.judgeQuestionWrong"></panDuan>
      </div>
      <div v-else-if="['tian_kong'].includes(form.questionTypeBase)">
        <tianKong :serialNumber="props.serialNumber" v-model="form"></tianKong>
      </div>
      <div v-else-if="['wan_xing', 'xuan_tian'].includes(form.questionTypeBase)">
        <wanXingXuantian :serialNumber="props.serialNumber" v-model="form" @updateTiGan="updateTiGan"></wanXingXuantian>
      </div>
      <div v-else-if="form.questionTypeBase == 'dan_xuan' ||
        form.questionTypeBase == 'duo_xuan' ||
        form.questionTypeBase == 'any_xuan'
        ">
        <dan-xuan v-model="form"></dan-xuan>
      </div>
      <div v-else-if="form.questionTypeBase == 'wen_da'">
        <wen-da v-model="form"></wen-da>
      </div>
      <div v-else-if="form.questionTypeBase == 'lian_xian'">
        <LXian @getVal="getVal" v-model="form"></LXian>
      </div>
      <div v-else-if="form.questionTypeBase == 'yu_yin'">
        <yuyin v-model="form"></yuyin>
      </div>
      <div v-else-if="form.questionTypeBase == 'pai_xu'">
        <pai-xu v-model="form"></pai-xu>
      </div>
      <!-- <div v-else-if="form.questionTypeBase == 'mao_dian'">
        <mao-dian v-model="form"></mao-dian>
      </div> -->
      <div v-else-if="form.questionTypeBase == 'gai_cuo'">
        <Mistick v-model="form"></Mistick>
      </div>
      <div v-else-if="form.questionTypeBase == 'zong_he' || form.questionTypeBase == 'ting_li'">
        <el-row class="ZHtigan">
          <el-col :span="1" :offset="1" class="center" style="font-weight: bold">题干</el-col>
          <el-col :span="2" :offset="16">
            <el-dropdown trigger="click">
              <el-button type="primary">
                <el-icon class="el-icon--right">
                  <Plus />
                </el-icon>添加子题
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="addSonQuestion(item.code, item.name)"
                    :disabled="item.code == 'zong_he' || item.code == 'ting_li'" v-for="(item, i) in questiontypeList"
                    :key="i">{{ item.name }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
        <el-row class="pt20 pb20">
          <el-col :span="24" class="tiganIpt">
            <TinymceEditor v-model="form.subjectEditorValue" :height="100" />
          </el-col>
        </el-row>
        <el-row v-if="form.questionTypeBase == 'ting_li'">
          <strong>听力附件</strong>
        </el-row>
        <el-row v-if="form.questionTypeBase == 'ting_li'">
          <el-col :span="5">
            <el-upload ref="tingliuploadFile" show-file-list v-model:file-list="TinglifileList" :headers="{
              Authorization: 'Bearer ' + getToken(),
            }" :limit="1" :action="props.url.imgUpload" :on-success="TingliSuccess" :on-error="TinglionError"
              :on-exceed="TinglionExceed" list-type="mp3" :before-upload="TinglibeforeUpload" :on-preview="tinglipreview">
              <el-button type="primary">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip" style="color:red;">只能上传大小不超20M,后缀名为mp3的文件</div>
              </template>
            </el-upload>
          </el-col>
          <el-col :span="4">
            播放次数:
            <el-input style="width:50px" v-model="form.listenQuestionMessage.playCount"></el-input>
          </el-col>
          <el-col :span="24" class="tiganIpt center" style="margin-top:20px" v-if="form.questionTypeBase == 'ting_li'">
            <span>听力原文:&nbsp;&nbsp;</span>
            <TinymceEditor style="width:93%;" v-model="form.originalText" :height="100" />
          </el-col>
        </el-row>

        <div v-for="(item, i) in form.subQuestionList" :key="item.questionUuid" class="sonQuestion">
          <el-row class="pt20 pb20 ZHSmall center">
            <el-col :span="6" class="center2">
              {{ i + 1 }}:
              <span style="font-weight: bold;margin-right:6px">{{ item.questionTypeName }}</span>
              <span>
                <el-input v-model="item.percentUiValue" style="width: 50px"></el-input>%
              </span>
            </el-col>
            <el-col :span="5" :offset="13">
              <el-button :icon="CloseBold" type="danger" @click="clearSonQuesition(i)">删除</el-button>
              <el-button :icon="ArrowDownBold" type="primary" @click="showSonQuesition(i)">收拢</el-button>
            </el-col>
          </el-row>
          <el-row v-show="item.show" class="pt20 pb20">
            <el-col :span="24">
              <div v-if="item.questionTypeBase == 'pan_duan'">
                <pan-duan v-model="form.subQuestionList[i]" :zhengque="config.judgeQuestionRight"
                  :cuowu="config.judgeQuestionWrong"></pan-duan>
              </div>
              <div v-else-if="item.questionTypeBase == 'tian_kong'">
                <tianKong v-model="form.subQuestionList[i]"></tianKong>
              </div>
              <div v-else-if="item.questionTypeBase == 'dan_xuan' ||
                item.questionTypeBase == 'duo_xuan' ||
                item.questionTypeBase == 'any_xuan'
                ">
                <dan-xuan v-model="form.subQuestionList[i]"></dan-xuan>
              </div>
              <div v-else-if="item.questionTypeBase == 'wen_da'">
                <wen-da v-model="form.subQuestionList[i]"></wen-da>
              </div>
              <div v-else-if="item.questionTypeBase == 'yu_yin'">
                <yuyin v-model="form.subQuestionList[i]"></yuyin>
              </div>
              <div v-else-if="item.questionTypeBase == 'pai_xu'">
                <pai-xu v-model="form.subQuestionList[i]"></pai-xu>
              </div>
              <!-- <div v-else-if="item.questionTypeBase == 'mao_dian'">
                <mao-dian v-model="form.subQuestionList[i]"></mao-dian>
              </div> -->
              <div v-else-if="item.questionTypeBase == 'lian_xian'">
                <LXian v-model="form.subQuestionList[i]"></LXian>
              </div>
              <div v-else-if="item.questionTypeBase == 'gai_cuo'">
                <Mistick v-model="form.subQuestionList[i]"></Mistick>
              </div>
              <div v-else-if="['wan_xing', 'xuan_tian'].includes(item.questionTypeBase)">
                <wanXingXuantian v-model="form.subQuestionList[i]" @updateTiGan="updateTiGanzh($event, i)">
                </wanXingXuantian>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <el-table v-if="fileTabelList.length > 0" :data="fileTabelList" style="width: 100%">
        <el-table-column prop="field-name" label="资源名称" align="center" />
        <el-table-column prop="field-author" label="作者" align="center" />
        <el-table-column prop="field-fileContentType" label="类型" align="center">
          <template #default="scope">
            <span v-if="scope.row['field-fileType'] == 'others'">相关资源</span>
            <span v-if="scope.row['field-fileType'] == 'tg'">题干文件</span>
            <span v-if="scope.row['field-fileType'] == 'jx'">试题解析</span>
            ({{ scope.row['field-fileContentType'] }})
          </template>
        </el-table-column>
        <el-table-column prop="field-fileSize" label="文件大小" align="center" />
        <el-table-column prop="address" label="操作">
          <template #default="scope">
            <el-tooltip content="查看" placement="top" effect="light">
              <el-button type="primary" @click="flieLook(scope.row['field-path'])" link :icon="View" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top" effect="light">
              <el-button type="primary" @click="flieEdit(scope.row)" link :icon="Edit" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="primary" @click="fileDelete(scope.row)" link :icon="Delete" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="examBottom">
      <div style="float:left;display:inline-block;margin-top:6px;">
        <el-button type="primary" text :icon="Plus" @click="addFileDialog()">添加相关资源</el-button>
      </div>
      <el-button v-if="!props.serialNumber" size="large" type="primary" :icon="Document"
        @click="submit(2)">保存并录入下一题</el-button>
      <el-button plain size="large" type="primary" :icon="Document" @click="submit(1)">保存并返回</el-button>
      <el-button type="danger" size="large" plain :icon="CloseBold" @click="submit(4)">关闭</el-button>
    </div>
    <el-dialog v-model="uploadDialog" :close-on-press-escape="false" :close-on-click-modal="false" title="资源" width="30%"
      :before-close="handleClose" @close="closeUploadDialog">
      <el-form ref="uploadFormRef" :model="fileForm" :rules="attachObjectRules" label-width="120px" class="demo-ruleForm"
        status-icon>
        <el-form-item label="资源名称：" prop="name">
          <el-input style="width:90%" v-model="fileForm.name" />
        </el-form-item>
        <el-form-item label="资源类型：" prop="fileType">
          <el-select style="width:90%" v-model="fileForm.fileType" placeholder="相关资源">
            <el-option label="相关资源" value="others" />
            <el-option label="题干文件(音视频,图片)" value="tg" />
            <el-option label="试题解析(音视频,图片)" value="jx" />
          </el-select>
        </el-form-item>
        <el-form-item label="作者：" prop="author">
          <el-input style="width:90%" v-model="fileForm.author" />
        </el-form-item>
        <el-form-item label="附件：">
          <el-upload ref="uploadFile" style="width:90%" v-model:file-list="fileList" show-file-list
            :action="props.url.imgUpload" :headers="{
              Authorization: 'Bearer ' + getToken(),
            }" :on-remove="handleRemove" :limit="1" :on-success="onSuccess" :on-error="onError" :on-exceed="onExceed">
            <el-button type="primary">选择文件</el-button>
            <el-button type="success" v-if="fileEditORadd" @click="flieLook(fileForm.path)">预览</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="fileBtn">确定</el-button>
          <el-button @click="uploadDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ct-add-question">
import request from '../../utils/require'
import { getCurrentInstance, toRefs, ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { JsonBase, uuid32 } from "../../utils/paper";
import { getToken, setToken } from "../../utils/auth";
import { Base64 } from "js-base64";
import { uuid } from "vue3-uuid";
import { ElLoading, ElMessageBox, ElMessage } from "element-plus";
import { handleTree } from '../../utils/power'
import TinymceEditor from '../component/Editor/index.vue'
const emit = defineEmits(["update:modelValue", 'close', 'save', 'saveBack']);
import {
  CirclePlus,
  Plus,
  CloseBold,
  ArrowDownBold,
  Document,
  View,
  Delete,
  Edit,
} from "@element-plus/icons-vue";
import panDuan from "./panDuan.vue";
import tianKong from "./tianKong.vue";
import danXuan from "./danXuan.vue";
import wenDa from "./wenDa.vue";
import paiXu from "./paiXu.vue";
// import maoDian from "./maoDian.vue";
import wanXingXuantian from "./WanxingXuantian.vue";
import yuyin from "./yuyin.vue";
import LXian from './lianXian.vue'
import Mistick from './mistick.vue'
const props = defineProps({
  data: {
    type: Object,
    default: null
  },
  checkout: {
    type: [String,Number],
    default: '1'
  },
  addType: {//不传或传0点击保存会调用爱习题接口保存到爱习题，传1保存到本地
    type: String,
    default: '0'
  },
  serialNumber: {//试题编号，修改时传入
    type: String,
    default: ""
  },
  questionUuid: {//试题uuid,传入即为修改试题
    type: String,
    default: null
  },
  questionDbId: {//题库ID
    type: [String, Number],
    default: null
  },
  questionConfig: {//题库配置,如果没有传入会调用爱习题接口查询
    type: Object,
    default: null
  },
  questionType: {
    type: String,
    default: null
  },
  token: {
    type: String,
    default: null
  },
  domainName:{
    type:String,
    default:'https://ct.hep.com.cn'
  },
  tinymceUrl: {
    type: String,
    default: 'https://ct.hep.com.cn/ct-api-online/api/oss/aliyun/upload'
  },

  url: {//接口地址
    type: Object,
    default: {
      imgUpload: "https://ct.hep.com.cn/ct-api-online/api/oss/aliyun/upload",//文件上传地址
      exam_resources: 'https://ct.hep.com.cn/ct-api-online/api/data/search/exam_resources',//获取附件列表
      questiondb_allpz: 'https://ct.hep.com.cn/ct-api-online/api/data/search/questiondb_allpz',//获取题库配置
      addSubmit: 'https://ct.hep.com.cn/ct-api-online/api/commonPage/question/addSubmit',//保存试题
      get: 'https://ct.hep.com.cn/ct-api-online/api/commonPage/question/get',//获取试题详情
      resources_add: 'https://ct.hep.com.cn/ct-api-online/api/data/search/resources_add',//新增附件
      resources_delete: 'https://ct.hep.com.cn/ct-api-online/api/data/search/resources_delete',//删除附件
      question_updatejson: 'https://ct.hep.com.cn/ct-api-online/api/data/search/question_updatejson',//修改附件
    }
  }
})
const { ctx, proxy } = getCurrentInstance();
const {
  toolbarTips,
  affixZIndex,
  EditShow,
  inputWidth,
  defaultList,
  usefulList,
  config,
  questiontypeList,
  form,
  difficultList,
  abilityList,
  attachObject,
  attachObjectRules,
  knowledgeList,
  questionAll,
  fileForm,
  fileList,
  TinglifileList,
  fileTabelList,
  questionJsonContent,
  urlCont,
  notDesc,
  notVisible,
  ticketDesc,
  ticketVisible,
  status,
  examTypeList,
  requireList
} = toRefs(
  reactive({
    toolbarTips: true,
    affixZIndex: 100,
    requireList: [],
    examTypeList: [],
    status: localStorage.getItem("status") || null || undefined || "",
    notDesc: "",
    notVisible: false,
    ticketDesc: "",
    ticketVisible: false,
    EditShow: true,
    inputWidth: 214,
    urlCont: 1,
    questionJsonContent: {},
    fileTabelList: [],
    fileList: [],
    TinglifileList: [],
    defaultList: [],
    questionAll: {},
    config: {},
    questiontypeList: [], //题型
    knowledgeList: [],
    form: {
      questionUuid: null,
      questionTypeBase: "",
      questionTypeName: "",
      knowledge: [
        {
          knowledgeName: "",
          percentUiValue: "100",
          knowledgeId: null,
        },
      ],
      remarks: "", //试题备注
      provider: "", //提供者
      subjectEditorValue: "", //题干
      options: [],
      LXvalModel: { // 连线
        list: {
          left: [],
          right: []
        },
        connections: [],
        isAnyChange: false
      },
      mistakeAnswer: {
        "mistake": [],
        "front": [],
        "end": [],
        "revise": [],
        "answer": ''
      },
      explainEditorValue: "", //试题解析
      explainEditorShow: false, //是否显示解析
      basicData: {
        "questionBasic-basicAbility": "", //能力
        "questionBasic-basicUseful": [], //题目用途
        "questionBasic-basicDifficult": "", //难易程度
        "questionBasic-oldSerialNumber": "", //编号
        "questionBasic-exampleQuestion": "", //例题号
        "questionBasic-basicStatus": "1",
        "questionBasic-optionCanShuffle": "", //选项随机 1允许 2不允许
        "questionBasic-schoolType": "", //学校类型
        "questionBasic-majorType": "", //专业类型
        "questionBasic-relationGroupId": "", //相关题组
        "questionBasic-equalGroupId": "", //等效题组
        "questionBasic-excludeGroupId": "", //互斥题组
        "questionBasic-zhenTi": "1", //是否真题
        "questionBasic-zhenTiProp": "", //真题属性
        "questionBasic-zhenTiSchool": "", //真题学校
        "questionBasic-zhenTiYear": "", //真题年份
        "questionBasic-require": '',//教学要求度
        "questionBasic-examType": '',//考试类型
      },
      attachObject: {},
      maodianObject: {
        allAngList: [],
        imgUrl: "",
        str: null,
        svgStr: null,
      },

      listenQuestionMessage: {
        fileContentType: "",
        fileName: "",
        filePath: "",
        fileRealName: "",
        fileType: ".mp3",
        playCount: "1",
      },
      originalText: "",
    },
    usefulList: [],
    difficultList: [],
    abilityList: [],
    fileForm: {
      name: "",
      fileType: "others",
      author: "",
    },
    attachObjectRules: {
      name: [{ required: true, message: "请填写资源名称", trigger: "blur" }],
      fileType: [
        { required: true, message: "请选择相关资源", trigger: "blur" },
      ],
      author: [{ required: true, message: "请填写作者", trigger: "blur" }],
    },
  })
);
onMounted(() => {
  if (props.tinymceUrl) localStorage.setItem('tinymceUrl', props.tinymceUrl)
  if(props.domainName) localStorage.setItem('domainName',props.domainName)
  if (window.MathJax) {
    window.MathJax = undefined;
    delete window.MathJax;
  }
  const script = document.createElement("script");
  script.src = "https://node2d-public.hep.com.cn/mathjax@3/es5/tex-mml-chtml.js";
  document.head.appendChild(script);
  if (props.token != null) {
    setToken(props.token)
  }
  getList()
  setInterval(() => {
    let boo = false
    const elements = document.querySelectorAll('div.tox.tox-tinymce.tox-tinymce-inline')
    if (elements.length > 0) {
      boo = [...elements].some(div => div.style.display === 'flex');
    }
    affixZIndex.value = boo ? 100 : -999;
    toolbarTips.value = !boo
  }, 100)
})
//还原
const jsonReversalArr = () => {
  //对象转数组
  fileTabelList.value = [];
  for (const key in form.value.attachObject) {
    if (form.value.attachObject[key] instanceof Array) {
      form.value.attachObject[key].forEach((res) => {
        fileTabelList.value.push(res);
      });
    } else {
      fileTabelList.value.push(form.value.attachObject[key]);
    }
  }
  // ctx.$forceUpdate();
};
const getVal = (e) => {
  console.log(e);
}
let loadingCreate = ref(null)
const dataRestore = async (res) => {
  let subjectContentPreview = res.data.subjectContentPreview;
  let json = JSON.parse(JSON.stringify(res.data));
  res.data = JSON.parse(res.data.questionJsonContent);
  console.log(res.data);
  res.data = JsonBase(res.data);
  res.data.questionTypeId = json.questionTypeId || 0;
  res.data.subjectContentPreview = subjectContentPreview;
  questionJsonContent.value = res.data;
  //获取资源
  if (props.questionUuid) {
    await getFileData("create");
  }
  var arr = [];
  if (localStorage.getItem("clear")) {
    questionJsonContent.value.knowledge = [
      { knowledgeName: "", percentUiValue: "100", knowledgeId: "" },
    ];
    questionJsonContent.value.basicData["questionBasic-basicUseful"] = "";
    questionJsonContent.value.basicData["questionBasic-majorType"] = "";
    questionJsonContent.value.basicData["questionBasic-schoolType"] = "";
    questionJsonContent.value.basicData["questionBasic-basicAbility"] =
      "";
    questionJsonContent.value.basicData["questionBasic-basicDifficult"] =
      "";
    questionJsonContent.value.basicData["questionBasic-relationGroupId"] =
      "";
    questionJsonContent.value.basicData["questionBasic-equalGroupId"] =
      "";
    questionJsonContent.value.basicData["questionBasic-excludeGroupId"] =
      "";
    questionJsonContent.value.basicData["questionBasic-schoolType"] = "";
    questionJsonContent.value.basicData["questionBasic-majorType"] = "";
  } else {
    if (
      questionJsonContent.value.basicData["questionBasic-basicUseful"]
    ) {
      questionJsonContent.value.basicData[
        "questionBasic-basicUseful"
      ].forEach((item) => {
        arr.push(Number(item));
      });
    } else {
      questionJsonContent.value.basicData["questionBasic-basicUseful"] =
        [];
    }

    questionJsonContent.value.basicData["questionBasic-majorType"] =
      Number(
        questionJsonContent.value.basicData["questionBasic-majorType"]
      );
    questionJsonContent.value.basicData["questionBasic-schoolType"] =
      Number(
        questionJsonContent.value.basicData["questionBasic-schoolType"]
      );

    questionJsonContent.value.basicData["questionBasic-basicUseful"] =
      arr;
    questionJsonContent.value.basicData["questionBasic-basicAbility"] =
      questionJsonContent.value.basicData["questionBasic-basicAbility"]
        ? Number(
          questionJsonContent.value.basicData[
          "questionBasic-basicAbility"
          ]
        )
        : "";
    questionJsonContent.value.basicData["questionBasic-basicDifficult"] =
      questionJsonContent.value.basicData["questionBasic-basicDifficult"]
        ? Number(
          questionJsonContent.value.basicData[
          "questionBasic-basicDifficult"
          ]
        )
        : "";
    questionJsonContent.value.knowledge.forEach((item) => {
      item.knowledgeId = Number(item.knowledgeId);
    });
  }
  if (questionJsonContent.value.subjectEditorValue) {
    questionJsonContent.value.subjectEditorValue =
      questionJsonContent.value.subjectEditorValue.indexOf('src="..') ==
        -1
        ? questionJsonContent.value.subjectEditorValue
        : questionJsonContent.value.subjectEditorValue.replace(
          /src="\.\./g,
          'src="' + settings.apiPath
        );
    questionJsonContent.value.subjectEditorValue = questionJsonContent.value.subjectEditorValue.indexOf('/ct-api-online/ct-api-online') == -1 ?
      questionJsonContent.value.subjectEditorValue : questionJsonContent.value.subjectEditorValue.replace(
        '/ct-api-online/ct-api-online',
        '/ct-api-online'
      );
  }
}
const restore = async () => {
  loadingCreate.value = ElLoading.service({
    lock: true,
    text: "数据处理中...",
    background: "rgba(255, 255, 255, 0.8)",
  });
  try {
    if (!props.serialNumber) localStorage.removeItem("questionUuid");
    if (props.questionUuid) {
      await request.post(props.url.get, {
        questionId: props.questionUuid
      }).then(
        async (res) => {
          dataRestore(res)
        }
      );
    }
    if (props.data) {
      dataRestore({ data: props.data })
    }
    if (props.data || props.questionUuid) {
      form.value = questionJsonContent.value;
      form.value.explainEditorShow =
        form.value.explainEditorValue && form.value.explainEditorValue.length > 0;
      form.value.options &&
        form.value.options.forEach((element) => {
          element.optionTipEditorShow = element.optionTipEditorValue?.length > 0;
        });
      jsonReversalArr();
      if (questionJsonContent.value.questionTypeBase == "ting_li") {
        TinglifileList.value.push({
          name: questionJsonContent.value.listenQuestionMessage.fileName,
          percentage: 100,
          path: questionJsonContent.value.listenQuestionMessage.filePath,
          status: "success",
        });
      }
      if (
        form.value.questionTypeBase == "zong_he" ||
        form.value.questionTypeBase == "ting_li"
      ) {
        form.value.subQuestionList.forEach((res) => {
          res.show = true;
        });
      }
    }
  } finally {
    loadingCreate.value.close();
  }

};
onBeforeUnmount(() => {
  localStorage.removeItem("questionUuid");
  localStorage.removeItem("type");
  localStorage.removeItem("clear");
})
restore();
//听力上传附件
const TingliSuccess = (res, file) => {
  form.value.listenQuestionMessage.fileContentType = file.raw.type;
  form.value.listenQuestionMessage.fileName = file.name;
  form.value.listenQuestionMessage.filePath = res.path;
  form.value.listenQuestionMessage.fileRealName = uuid32();
};
const TinglionError = () => {
  ElMessage.error("上传失败!");
};
const tingliuploadFile = ref(null);
const TinglionExceed = (files) => {
  //覆盖上一个文件
  tingliuploadFile.value.clearFiles();
  const file = files[0];
  tingliuploadFile.value.handleStart(file);
  tingliuploadFile.value.submit();
};
const TinglibeforeUpload = (file) => {
  let boo = true;
  if (file.type != "audio/mpeg") {
    boo = false;
    ElMessage.error("请上传后缀名为.mp3的文件!");
  }
  if (file.size > 20971520) {
    boo = false;
    ElMessage.error("请上传20M以内的文件!");
  }
  return boo;
};
//上传附件代码区
const tinglipreview = (file) => {
  window.open(proxy.apiPath + file.path, "_blank");
};
const fileEditORadd = ref(false);
const uploadFile = ref(null);
const onSuccess = (res, file) => {
  //上传成功
  fileForm.value.path = res.path;
  fileForm.value.size = file.raw.size;
  fileForm.value.type = file.raw.type;
};
const onExceed = (files) => {
  //覆盖上一个文件
  uploadFile.value.clearFiles();
  const file = files[0];
  uploadFile.value.handleStart(file);
  uploadFile.value.submit();
};
const handleRemove = (file) => {
  //删除已上传文件
};
const onError = () => {
  //上传失败
  ElMessage.error("上传失败!");
};
const addFileDialog = () => {
  uploadDialog.value = true;
  fileEditORadd.value = false;
};
const uploadFormRef = ref(null);
//获取附件列表
const getFileData = async (create) => {
  await request.post(props.url.exam_resources, {
    questionUuid: questionJsonContent.value.questionUuid
  }).then((res) => {
    let otherFile = [];
    let tgFile = [];
    let jxFile = [];
    res.data.forEach((item) => {
      switch (item["field-fileType"]) {
        case "others":
          otherFile.push(item);
          break;
        case "tg":
          tgFile.push(item);
          break;
        case "jx":
          jxFile.push(item);
          break;
      }
    });
    let json = {
      otherFile,
      tgFile,
      jxFile,
    };
    if (create) {
      questionJsonContent.value.attachObject = json;
    } else {
      form.value.attachObject = json;
      request.post(props.url.question_updatejson, {
        attachObject: json,
        uuid: form.value.questionUuid,
      })
    }
  });
};
const fileBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "数据处理中...",
    background: "rgba(255, 255, 255, 0.7)",
  });
  uploadFormRef.value.validate(async (valid) => {
    let boo = fileEditORadd.value ? true : fileList.value.length > 0;
    if (valid && boo) {
      switch (fileForm.value.fileType) {
        case "others":
          form.value.attachObject.otherFile
            ? ""
            : (form.value.attachObject.otherFile = []);
          if (!form.value.attachObject.otherFile instanceof Array) {
            let arr = [form.value.attachObject.otherFile];
            form.value.attachObject.otherFile = arr;
          }
          let others = {
            "field-name": fileForm.value.name,
            "field-fileType": fileForm.value.fileType,
            "field-author": fileForm.value.author,
            "field-path": fileForm.value.path,
            "field-questionUuid": questionJsonContent.value.questionUuid,
            "field-fileSize": fileForm.value.size,
            "field-fileContentType": fileForm.value.type,
          };
          let json = {};
          json.name = others["field-name"];
          json.fileType = others["field-fileType"];
          json.author = others["field-author"];
          json.path = others["field-path"];
          json.questionUuid = others["field-questionUuid"];
          json.fileSize = others["field-fileSize"];
          json.fileContentType = others["field-fileContentType"];
          json.name = others["field-name"];
          if (fileEditORadd.value) {
            json.id = fileForm.value.id;
          } else {
            //新增
            form.value.attachObject.otherFile.push(others);
          }
          await request.post(props.url.resources_add, {
            json
          })
          break;
        case "tg":
          form.value.attachObject.tgFile
            ? ""
            : (form.value.attachObject.tgFile = []);
          if (!form.value.attachObject.tgFile instanceof Array) {
            let arr = [form.value.attachObject.tgFile];
            form.value.attachObject.tgFile = arr;
          }
          let tg = {
            "field-name": fileForm.value.name,
            "field-fileType": fileForm.value.fileType,
            "field-author": fileForm.value.author,
            "field-path": fileForm.value.path,
            "field-questionUuid": questionJsonContent.value.questionUuid,
            "field-fileSize": fileForm.value.size,
            "field-fileContentType": fileForm.value.type,
          };
          let tgjson = {};
          tgjson.name = tg["field-name"];
          tgjson.fileType = tg["field-fileType"];
          tgjson.author = tg["field-author"];
          tgjson.path = tg["field-path"];
          tgjson.questionUuid = tg["field-questionUuid"];
          tgjson.fileSize = tg["field-fileSize"];
          tgjson.fileContentType = tg["field-fileContentType"];
          tgjson.name = tg["field-name"];
          if (fileEditORadd.value) {
            tgjson.id = fileForm.value.id;
          } else {
            form.value.attachObject.tgFile.push(tg);
          }
          await request.post(props.url.resources_add, {
            tgjson
          })
          break;
        case "jx":
          form.value.attachObject.jxFile
            ? ""
            : (form.value.attachObject.jxFile = []);
          if (!form.value.attachObject.jxFile instanceof Array) {
            let arr = [form.value.attachObject.jxFile];
            form.value.attachObject.jxFile = arr;
          }
          let jx = {
            "field-name": fileForm.value.name,
            "field-fileType": fileForm.value.fileType,
            "field-author": fileForm.value.author,
            "field-path": fileForm.value.path,
            "field-questionUuid": questionJsonContent.value.questionUuid,
            "field-fileSize": fileForm.value.size,
            "field-fileContentType": fileForm.value.type,
          };
          let jxjson = {};
          jxjson.name = jx["field-name"];
          jxjson.fileType = jx["field-fileType"];
          jxjson.author = jx["field-author"];
          jxjson.path = jx["field-path"];
          jxjson.questionUuid = jx["field-questionUuid"];
          jxjson.fileSize = jx["field-fileSize"];
          jxjson.fileContentType = jx["field-fileContentType"];
          jxjson.name = jx["field-name"];
          if (fileEditORadd.value) {
            jxjson.id = fileForm.value.id;
          } else {
            form.value.attachObject.jxFile.push(jx);
          }
          await request.post(props.url.resources_add, {
            jxjson
          })
          break;
      }
      await getFileData();
      jsonReversalArr();
      uploadDialog.value = false;
      fileForm.value = {
        name: "",
        fileType: "others",
        author: "",
      };
      uploadFile.value.clearFiles();
      fileEditORadd.value = false;
    } else {
      if (valid) {
        ElMessage.error("请上传文件!");
      }
    }
  });
  loading.close();
};
const userfulChange = () => {
  getWidth();
};
const userfulWidth = ref(0);
const getWidth = () => {
  userfulWidth.value =
    form.value.basicData["questionBasic-basicUseful"].length != 0
      ? form.value.basicData["questionBasic-basicUseful"].length * 16
      : 20;
};
const flieLook = (url) => {
  //查看文件
  window.open(proxy.apiPath + url, "_blank");
};
const flieEdit = (row) => {
  //修改文件
  fileForm.value.path = row["field-path"];
  fileForm.value.size = row["field-fileSize"];
  fileForm.value.type = row["field-fileContentType"];
  fileForm.value.name = row["field-name"];
  fileForm.value.fileType = row["field-fileType"];
  fileForm.value.author = row["field-author"];
  fileForm.value.uuid = row["field-questionUuid"];
  fileForm.value.id = row["fieldCon-id"];
  fileEditORadd.value = true;
  uploadDialog.value = true;
};
const fileDelete = (row) => {
  ElMessageBox.confirm("确认要删除此条资源吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    request.post(props.url.resources_delete, {
      id: row["fieldCon-id"]
    }).then(async (res) => {
      await getFileData();
      jsonReversalArr();
      ElMessage.success("删除成功!");
    });
  });
};
const knowledgeListName = ref(null);
const formIpt = ref(null);
const getList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(255, 255, 255, 0.8)",
  });
  if (props.questionDbId == null) return ElMessage.error('参数错误!缺少questionDbId')
  if (props.questionType == null) return ElMessage.error('参数错误!缺少questionType')
  const fn = (res) => {
    questionAll.value = res;
    knowledgeListName.value = res.knowledge;
    res.knowledge.forEach((item) => {
      item.value = item.id;
      item.label = item.name;
    });
    knowledgeList.value = handleTree(res.knowledge);
    defaultList.value.push(knowledgeList.value[0].id);
    questiontypeList.value = res.type;
    config.value = res.config;
    usefulList.value = res.useful;
    if (config.value.useful == "1" && !props.questionUuid) {
      usefulList.value.forEach((k) => {
        //题目用途默认全选
        form.value.basicData["questionBasic-basicUseful"].push(k.id);
      });
    }
    difficultList.value = res.difficult;
    abilityList.value = res.ability;
    requireList.value = res.require
    examTypeList.value = res.exam_type
    questiontypeList.value.forEach((item) => {
      if (item.code == "wen_da" || item.code == "yu_yin") {
        item.disabled = true;
      }
    });
    if (!props.questionUuid) Base();
    userfulChange();
  }
  if (props.questionConfig == null) {
    request.post(props.url.questiondb_allpz, {
      id: props.questionDbId
    }).then(
      (res) => {
        fn(res.data)
      }
    );
  } else {
    fn(props.questionConfig)
  }
  loading.close();
};
const restoreForm = (type, knowledge) => {
  //还原form表单
  let basicData = form.value.basicData["questionBasic-basicUseful"];
  if (type == 2) {
    form.value.knowledge = knowledge;
  } else {
    form.value.knowledge = [
      {
        knowledgeName: "",
        percentUiValue: "100",
        knowledgeId: "",
      },
    ];
  }
  form.value.originalText = "";
  form.value.questionUuid = null;
  form.value.remarks = ""; //试题备注
  form.value.provider = ""; //提供者
  form.value.subjectEditorValue = ""; //题干
  form.value.options = [];
  form.value.explainEditorValue = ""; //试题解析
  form.value.explainEditorShow = false; //是否显示解析
  form.value.restoreForm = [];
  form.value.attachObject = {};
  form.value.answerEditorValue = "";
  jsonReversalArr();
  form.value.basicData = {
    "questionBasic-basicAbility": "",
    "questionBasic-basicDifficult": "", //难易程度
    "questionBasic-oldSerialNumber": "", //编号
    "questionBasic-exampleQuestion": "", //例题号
    "questionBasic-basicStatus": "1",
    "questionBasic-optionCanShuffle": "", //选项随机 1允许 2不允许
    "questionBasic-schoolType": "", //学校类型
    "questionBasic-majorType": "", //专业类型
    "questionBasic-relationGroupId": "", //相关题组
    "questionBasic-equalGroupId": "", //等效题组
    "questionBasic-excludeGroupId": "", //互斥题组
    "questionBasic-zhenTi": "1", //是否真题
    "questionBasic-zhenTiProp": "", //真题属性
    "questionBasic-zhenTiSchool": "", //真题学校
    "questionBasic-zhenTiYear": "", //真题年份
    "questionBasic-require": '',//教学要求度
    "questionBasic-examType": '',//考试类型
  };
  form.value.basicData["questionBasic-basicUseful"] = basicData;
  form.value.listenQuestionMessage = {
    fileContentType: "",
    fileName: "",
    filePath: "",
    fileRealName: "",
    fileType: ".mp3",
    playCount: "1",
  };
  TinglifileList.value = [];
  fileList.value = [];
};
const knowledgeShow = ref(false);
setTimeout(() => {
  //切换试题还原知识点
  knowledgeShow.value = true;
}, 1000);
const queryQuestionTypeBase = (type, knowledge) => {
  knowledgeShow.value = false;
  const loading = ElLoading.service({
    lock: true,
    text: "切换中...",
    background: "rgba(255, 255, 255, 0.7)",
  });
  restoreForm(type, knowledge);
  localStorage.setItem("type", form.value.questionTypeBase);
  //判断当前题型
  if (["wan_xing", "tian_kong", 'xuan_tian'].includes(form.value.questionTypeBase)) {
    form.value.subjectEditorValue = "";
  }
  if (form.value.questionTypeBase == "pan_duan") {
    for (let index = 0; index < 2; index++) {
      form.value.options.push({
        optionUuid: uuid.v4(),
        optionIndex: index + 1,
        optionTipEditorValue: "",
        optionTipEditorShow: false,
        optionTextValue:
          index == 0
            ? config.value.judgeQuestionRight
            : config.value.judgeQuestionWrong,
        isAnswer: false,
      });
    }
  } else if (
    form.value.questionTypeBase == "dan_xuan" ||
    form.value.questionTypeBase == "duo_xuan" ||
    form.value.questionTypeBase == "any_xuan"
  ) {
    let count = deep(
      questiontypeList.value.filter(
        (item) => item.code == form.value.questionTypeBase
      )
    )[0].optionCount;
    for (let index = 0; index < Number(count); index++) {
      if (form.value.questionTypeBase == "any_xuan") {
        form.value.options.push({
          optionUuid: uuid.v4(),
          optionIndex: index + 1,
          optionTipEditorValue: "",
          optionTextValue: "",
          isAnswer: false,
          optionTipEditorShow: false,
          optionPercentValue: "100",
        });
      } else {
        form.value.options.push({
          optionUuid: uuid.v4(),
          optionIndex: index + 1,
          optionTipEditorValue: "",
          optionTextValue: "",
          isAnswer: false,
          optionTipEditorShow: false,
        });
      }
    }
  } else if (
    form.value.questionTypeBase == "wen_da" ||
    form.value.questionTypeBase == "yu_yin"
  ) {
    form.value.yuyinType = ''
    form.value.keywordEditorValue = "";
    form.value.keyList = [];
  } else if (form.value.questionTypeBase == "pai_xu") {
    for (let index = 0; index < 4; index++) {
      form.value.options.push({
        optionUuid: uuid.v4(),
        optionIndex: index + 1,
        optionTipEditorValue: "",
        optionTextValue: "",
        optionPaiXuValue: index + 1,
      });
    }
  } else if (
    form.value.questionTypeBase == "zong_he" ||
    form.value.questionTypeBase == "ting_li"
  ) {
    form.value.subQuestionList = [];
    // let end = setInterval(function () { }, 10000);
    // for (let i = 1; i <= end; i++) {
    //   clearInterval(i);
    // }
  } else if (form.value.questionTypeBase == "mao_dian") {
    form.value.maodianObject = {
      allAngList: [],
      imgUrl: "",
      str: null,
    };
  }
  setTimeout(() => {
    //切换试题还原知识点
    knowledgeShow.value = true;
    loading.close();
  }, 2500);
};
const deep = (json) => {
  return JSON.parse(JSON.stringify(json));
};
const questionSelect = () => {
  if (props.questionType) {
    // window.history.pushState(
    //   {},
    //   0,
    //   window.location.href.substring(0, window.location.href.indexOf("?")) +
    //   "?type=" +
    //   Base64.encodeURI(form.value.questionTypeName) +
    //   "&id=" +
    //   props.questionDbId
    // );
    // urlCont.value += 1;
    Base(Base64.encodeURI(form.value.questionTypeName));
  }
};
const Base = (res) => {
  //还原试题code与name
  if (res) {
    form.value.questionTypeBase = questionAll.value.type.filter(
      (item) => item.dbName == Base64.decode(res)
    )[0].code;
    form.value.questionTypeName =
      Base64.decode(res) || questionAll.value.type[0].dbName;
  } else {
    let dbList = questionAll.value.type.filter(
      (item) => item.dbName == props.questionType
    );
    if (dbList.length == 0) {
      dbList = questionAll.value.type.filter(
        (item) => item.name == props.questionType
      );
    }
    if (dbList.length == 0) return ElMessage.error('题型不正确')
    form.value.questionTypeBase = props.questionType
      ? dbList[0].code
      : questionAll.value.type[0].code;
    form.value.questionTypeName =
      props.questionType || questionAll.value.type[0].dbName;
  }
};
//监听用户选择题型
watch(
  () => form.value.questionTypeBase,
  (newVal, oldVal) => {
    if (!props.questionUuid) {
      queryQuestionTypeBase();
    }
  },
  { deep: true }
);
//监听问答题关键字拼接
watch(
  () => form.value.keyList,
  () => {
    form.value.keywordEditorValue = form.value.keyList.join(",");
  }
);
//知识点方法区
const knowAdd = () => {
  //新增知识点
  if (form.value.knowledge.length >= 3)
    return ElMessage.error("已达到最大数量!");
  form.value.knowledge.push({
    knowledgeName: "",
    percentUiValue: "",
    knowledgeId: null,
  });
  calculate();
};
const calculate = () => {
  //计算百分比
  let num = 0;
  form.value.knowledge.forEach((item) => {
    item.percentUiValue = Number(
      (100 / form.value.knowledge.length).toFixed(1)
    );
    num += item.percentUiValue;
  });
  if (num != 100) {
    form.value.knowledge[0].percentUiValue += 100 - num;
    form.value.knowledge[0].percentUiValue =
      form.value.knowledge[0].percentUiValue.toFixed(1);
  }
};
const KnowDel = (i) => {
  //删除
  if (form.value.knowledge.length <= 1)
    return ElMessage.error("已达到最小数量！");
  form.value.knowledge.splice(i, 1);
  calculate();
};
//编辑器方法区
//综合题添加子题
const addSonQuestion = (code, name) => {
  let json = {
    questionTypeBase: code,
    questionTypeName: name,
    questionUuid: uuid32(),
    questionIndex: form.value.subQuestionList.length,
    subjectEditorValue: "",
    explainEditorValue: "",
    options: [],
    percentUiValue: "0",
    show: true,
  };
  switch (code) {
    case "mao_dian":
      json.maodianObject = {
        allAngList: [],
        imgUrl: "",
        str: null,
      };
      break;
    case "yu_yin":
      json.yuyinType = ''
      json.keywordEditorValue = "";
      json.keyList = [];
      break;
    case "lian_xian":
      json.LXvalModel = { // 连线
        list: {
          left: [],
          right: []
        },
        connections: [],
        isAnyChange: false
      };
      break;
    case "gai_cuo":
      json.mistakeAnswer = {
        "mistake": [],
        "front": [],
        "end": [],
        "revise": [],
        "answer": ''
      };
      break;
    case "wen_da":
      json.keywordEditorValue = "";
      json.keyList = [];
      break;
    case "pan_duan":
      for (let index = 0; index < 2; index++) {
        json.options.push({
          optionUuid: uuid.v4(),
          optionIndex: index + 1,
          optionTipEditorValue: "",
          optionTipEditorShow: false,
          optionTextValue:
            index == 0
              ? config.value.judgeQuestionRight
              : config.value.judgeQuestionWrong,
          isAnswer: false,
        });
      }
      break;
    case "duo_xuan":
    case "any_xuan":
    case "dan_xuan":
      let count = deep(
        questiontypeList.value.filter((item) => item.code == code)
      )[0].optionCount;
      for (let index = 0; index < Number(count); index++) {
        if (code == "any_xuan") {
          json.options.push({
            optionUuid: uuid.v4(),
            optionIndex: index + 1,
            optionTipEditorValue: "",
            optionTextValue: "",
            isAnswer: false,
            optionTipEditorShow: false,
            optionPercentValue: "100",
          });
        } else {
          json.options.push({
            optionUuid: uuid.v4(),
            optionIndex: index + 1,
            optionTipEditorValue: "",
            optionTextValue: "",
            isAnswer: false,
            optionTipEditorShow: false,
          });
        }
      }
      break;
    default:
      break;
  }
  form.value.subQuestionList.push(json);
  form.value.subQuestionList.forEach((res, i) => {
    res.questionIndex = i + 1;
  });
};
const clearSonQuesition = (i) => {
  //删除子题
  ElMessageBox.confirm("确认要删除此题吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    form.value.subQuestionList.splice(i, 1);
    form.value.subQuestionList.forEach((res, i) => {
      res.questionIndex = i + 1;
    });
    ElMessage.success("删除成功");
  });
};
const showSonQuesition = (i) => {
  //收拢子题
  form.value.subQuestionList[i].show = !form.value.subQuestionList[i].show;
};
//上传资源方法区
const uploadDialog = ref(false);
const handleClose = (done) => {
  ElMessageBox.confirm("确定要关闭吗?").then(() => {
    done();
  });
};
const closeUploadDialog = () => {
  //关闭弹框
  fileEditORadd.value = false;
  uploadFile.value.clearFiles();
  fileForm.value = {
    name: "",
    fileType: "others",
    author: "",
  };
};
const addVerify = (val) => {
  //提交验证
  if (val.subjectEditorValue.length == 0)
    return {
      type: false,
      text: "请输入[" + val.questionTypeName + "]题干的内容!",
    };
  if (val.options.some((res) => res.optionTextValue.length == 0))
    return {
      type: false,
      text: "请输入[" + val.questionTypeName + "]选项的内容!",
    };
  if (["wan_xing", "tian_kong", 'xuan_tian'].includes(val.questionTypeBase) && val.options.length == 0)
    return { type: false, text: "请添加[" + val.questionTypeName + "]的选项!" };
  //单选题,判断题,多选题，选项是否有正确答案
  if (
    ["dan_xuan", "duo_xuan", "pan_duan", "any_xuan"].includes(
      val.questionTypeBase
    ) &&
    val.options.filter((res) => res.isAnswer == true).length == 0 && props.checkout == '1'
  )
    return {
      type: false,
      text: "请选择[" + val.questionTypeName + "]正确答案!",
    };
  //不定向填空选择百分比判断
  let num = 0;
  if (["any_xuan", "tian_kong"].includes(val.questionTypeBase)) {
    val.options.forEach((item) => {
      if (val.questionTypeBase == "any_xuan") {
        if (item.isAnswer) {
          num = accAdd(num, Number(item.optionPercentValue));
        }
      } else {
        num = accAdd(num, Number(item.optionPercentValue));
      }
    });
  }
  if (["any_xuan", "tian_kong"].includes(val.questionTypeBase) && num != 100)
    return {
      type: false,
      text: "[" + val.questionTypeName + "]选项百分比的和必须等于100!",
    };
  //去除题干p标签
  val.subjectEditorValue = claerP(val.subjectEditorValue);
  val.explainEditorValue = claerP(val.explainEditorValue);
  //去除选项p标签
  val.options.forEach((res) => {
    res.optionTextValue = claerP(res.optionTextValue);
  });
  return { type: true }; // 全部通过返回true
};
const notBtn = (type) => {
  if (type == 1) {
    ticketVisible.value = true;
  } else {
    notVisible.value = true;
  }
};
const isNumber = (text) => {
  return /^-?\d+(\.\d+)?%?$/.test(text);
}
const submit = async (type) => {
  //提交
  if (type == 4) {
    ElMessageBox.confirm(
      "确定要关闭吗?关闭后此次编辑的内容将不会被保存!",
      "警告",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).then(() => {
      emit("close", true);
    });
    return;
  }
  //判断是否真题，不是真题去除默认值
  if (config.value.zhenTi != "1")
    form.value.basicData["questionBasic-zhenTi"] = "";
  //判断知识点
  if (config.value.knowledge == "1" && form.value.knowledge.filter((res) => res.knowledgeId == "").length > 0)
    return ElMessage.error("请选择知识点!");
  //判断题目用途
  if (
    config.value.useful == "1" &&
    form.value.basicData["questionBasic-basicUseful"].length == 0
  )
    return ElMessage.error("请选择题目用途!");
  if (
    config.value.difficult == "1" &&
    form.value.basicData["questionBasic-basicDifficult"] == ""
  )
    return ElMessage.error("请选择难易程度!");
  if (
    config.value.ability == "1" &&
    form.value.basicData["questionBasic-basicAbility"] == ""
  )
    return ElMessage.error("请选择能力!");
  let paixuBoo = false;
  if (form.value.questionTypeBase == "pai_xu") {
    //排序题顺序重复校验
    let hash = {};
    const data2 = form.value.options.reduce((preVal, curVal) => {
      hash[curVal.optionPaiXuValue]
        ? ""
        : (hash[curVal.optionPaiXuValue] = true && preVal.push(curVal));
      return preVal;
    }, []);
    if (data2.length != form.value.options.length) {
      paixuBoo = true;
    }
  }
  if (form.value.questionTypeBase == "yu_yin" && form.value?.yuyinType == '') return ElMessage.error("[语音题]选择评测语言!");
  if (form.value.questionTypeBase == "yu_yin" && isNumber(form.value.subjectEditorValue.replace(/<[^>]+>/g, ''))) return ElMessage.error("[语音题]题干不能是纯数字!");
  if (paixuBoo) return ElMessage.error("[排序题]选项正确顺序重复!");
  //是否上传听力附件
  let tingliBoo = false;
  if (form.value.questionTypeBase == "ting_li") {
    if (TinglifileList.value.length == 0) {
      tingliBoo = true;
      ElMessage.error("请上传听力附件!");
    }
  } else {
    //去除听力字段
    form.value.listenQuestionMessage
      ? delete form.value.listenQuestionMessage
      : "";
    form.value.originalText ? delete form.value.originalText : "";
  }
  if (tingliBoo) return;
  //判断选项与题干是否有值
  let json = {};
  if (
    form.value.questionTypeBase != "zong_he" &&
    form.value.questionTypeBase != "ting_li"
  ) {
    //不是综合题
    json = addVerify(form.value);
  } else {
    //综合题
    if (form.value.subQuestionList.filter((i) => i.percentUiValue == "")[0])
      return ElMessage.error("请输入子题的百分比!");
    if (form.value.subjectEditorValue.length == 0) {
      //判断题干
      json = {
        type: false,
        text: "请输入[" + form.value.questionTypeName + "]题干的内容!",
      };
    } else {
      if (form.value.subQuestionList == 0) {
        //是否有子题
        json = { type: false, text: "请添加子题!" };
      } else {
        let num = 0;
        form.value.subQuestionList.forEach((j) => {
          num += Number(j.percentUiValue);
        });
        if (num != 100) {
          json = { type: false, text: "子题百分比的和必须等于100!" };
        } else {
          for (let j = 0; j < form.value.subQuestionList.length; j++) {
            json = addVerify(form.value.subQuestionList[j]);
            if (!json.type) break;
          }
        }
      }
    }
  }
  if (!json.type) return ElMessage.error(json.text);
  if (
    form.value.questionTypeBase == "zong_he" ||
    form.value.questionTypeBase == "ting_li"
  ) {
    form.value.subjectEditorValue = claerP(form.value.subjectEditorValue);
  }
  // 匹配知识点名称
  if (config.value.knowledge == "1") {
    form.value.knowledge.forEach((res) => {
      res.knowledgeName = knowledgeListName.value.filter(
        (item) => item.id == res.knowledgeId
      )[0].name;
    });
  }
  if (config.value.useful != "1")
    delete form.value.basicData["questionBasic-basicUseful"];
  if (config.value.difficult != "1")
    delete form.value.basicData["questionBasic-basicDifficult"];
  if (config.value.ability != "1")
    delete form.value.basicData["questionBasic-basicAbility"];
  if (config.value.zhenTi != "1") {
    delete form.value.basicData["questionBasic-zhenTi"];
    delete form.value.basicData["questionBasic-zhenTiProp"];
    delete form.value.basicData["questionBasic-zhenTiSchool"];
    delete form.value.basicData["questionBasic-zhenTiYear"];
  }
  if (config.value.relationGroup != "1")
    delete form.value.basicData["questionBasic-relationGroupId"];
  if (config.value.equalGroup != "1")
    delete form.value.basicData["questionBasic-equalGroupId"];
  if (config.value.excludeGroup != "1")
    delete form.value.basicData["questionBasic-excludeGroupId"];
  if (config.value.schoolType != "1")
    delete form.value.basicData["questionBasic-schoolType"];
  if (config.value.majorType != "1")
    delete form.value.basicData["questionBasic-majorType"];
  if (config.value.require != "1")
    delete form.value.basicData["questionBasic-require"];
  if (config.value.examType != "1")
    delete form.value.basicData["questionBasic-examType"];
  const loading = ElLoading.service({
    lock: true,
    text: "提交中",
    background: "rgba(255, 255, 255, 0.7)",
  });
  setTimeout(() => {
    loading.close();
  }, 2000);
  //锚点题选项处理
  if (form.value.questionTypeBase == "mao_dian") {
    form.value.options = form.value.maodianObject.allAngList;
  } else {
    delete form.value.maodianObject;
  }
  if (props.questionUuid) {
    if (type == 1) return emit("saveBack", {
      questionUuid: form.value.questionUuid,
      questionDbId: Number(props.questionDbId),
      questionTypeId: form.value.questionTypeId,
      questionData: form.value,
    })
    if (type == 2) return emit("save", {
      questionUuid: form.value.questionUuid,
      questionDbId: Number(props.questionDbId),
      questionTypeId: form.value.questionTypeId,
      questionData: form.value,
    })
  } else {
    //新增
    let questionUuid = uuid32();
    form.value.questionUuid = questionUuid;
    let backJson = {
      questionUuid,
      questionDbId: Number(props.questionDbId),
      questionTypeId: questiontypeList.value.filter(
        (k) => k.dbName == form.value.questionTypeName
      )[0].id,
      questionData: form.value,
    }
    if (type == 1) return emit("saveBack", backJson)
    if (type == 2) {
      emit("save", backJson)
      queryQuestionTypeBase(type, form.value.knowledge);
      EditShow.value = false;
      setTimeout(() => {
        form.value.subjectEditorValue = "";
        EditShow.value = true;
        form.value.mistakeAnswer = {
          "mistake": [],
          "front": [],
          "end": [],
          "revise": [],
          "answer": ''
        };
        form.value.LXvalModel = { // 连线
          list: {
            left: [],
            right: []
          },
          connections: [],
          isAnyChange: false
        };
      }, 2000);
      return
    }
    if (props.addType == '0') {
      request.post(props.url.addSubmit, {
        questionUuid,
        questionDbId: Number(props.questionDbId),
        questionTypeId: questiontypeList.value.filter(
          (k) => k.dbName == form.value.questionTypeName
        )[0].id,
        questionData: form.value,
      }).then((res) => { });
    }
  }
};
const claerP = (val) => {
  return val.indexOf("<p") == 0 ? val.substring(3, val.length - 4) : val;
};
const updateTiGan = (val) => {
  console.log(val);
  //修改题干内容
  form.value.subjectEditorValue = val
}

const updateTiGanzh = (val, i) => {
  console.log(val, i);
  //修改题干内容
  form.value.subQuestionList[i] = val
}
</script>
<style lang="scss" scoped>
.box {
  margin: 20px 20px 90px 20px;
  border: #e4e7ed 1px solid;
  background: #fff;
}

.top {
  border-bottom: #e4e7ed 1px solid;
  background: #f5f7fa;
  padding: 10px 20px;
  font-size: 14px;
}

.ipt,
.EditTin,
.buttonBox {
  padding: 20px;
}

.ipt {
  margin: 20px 20px 0 20px;
  border-bottom: #ebeef7 1px solid;
}

.mt {
  margin-top: 4px;
}

.addBtn {
  color: #358bf8;
  border-color: #358bf8;
}

.knowledge {
  height: 50px;

  .item {
    display: flex;
  }
}

.knowledge :deep(.el-input-group__append) {
  padding: 0 !important;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.center2 {
  display: flex;
  align-items: center;
}

.tigan {
  border-bottom: 1px solid #ccc;
}

.buttonBox {
  margin: 0;
}

.EditTin {
  margin-top: 0;
  margin-bottom: 50px;
}

.require::before {
  content: "*";
  display: inline-block;
  color: #f56c6c;
  transform: translate(-6px, 0px);
}

.Nengli::before {
  content: "*";
  display: inline-block;
  color: #f56c6c;
  transform: translate(23px, 4px);
  position: absolute;
}

.nanyidu::before {
  content: "*";
  display: inline-block;
  color: #f56c6c;
  transform: translate(14px, 4px);
  position: absolute;
}

.labelwidth {
  height: 32px;
  line-height: 32px;
  padding: 0 12px 0 17px;
  box-sizing: border-box;
  width: 85px;
  font-weight: 700;
  color: #606266;
  font-size: 14px;
}

.examBottom {
  background: #fff;
  text-align: right;
  align-items: center;
  padding: 15px 40px;
  box-shadow: 0px 2px 20px 0px rgb(33 33 33 / 9%);
  z-index: 20;
}

.ZHtigan {
  border-bottom: 1px dashed #dcdfe8;
  padding-bottom: 20px;
  margin-bottom: 10px;
}

.ZHSmall {
  background: #f0ecec;
}

.toolbarTips {
  width: 100%;
  height: 100%;
  font-size: 14px;
  color: #a1a9b8;
  background: url('./editorBG.png') center center;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
}

#EditTinId {
  position: relative;
  width: 100%;
  height: 90px;
  background-color: #f1f3f8;
}

.required {
  color: red;
  display: inline;
}
</style>